package com.estate.web.controller.report.home;

import com.estate.common.core.domain.AjaxResult;
import com.estate.system.domain.SysOperLog;
import com.estate.system.domain.vo.SuburbDetailVo;
import com.estate.system.domain.vo.SystemLogVo;
import com.estate.system.service.impl.DataEnquiriesServiceImpl;
import com.estate.system.service.impl.DataListingsServiceImpl;
import com.estate.system.service.impl.SysOperLogServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/home")
public class HomeBossController {

    @Resource
    private DataEnquiriesServiceImpl dataEnquiriesServiceImpl;
    @Resource
    private DataListingsServiceImpl dataListingsServiceImpl;
    @Resource
    private SysOperLogServiceImpl sysOperLogService;

    /**
     * 获取近七天新增客户咨询数量
     *
     * @param paramData key1:xDays 表示要查询最近x天的数据
     * @return sevenDaysAgoCount：最近7天数量  fourteenDaysAgoCount：上一个7天的数量 addPercentage:最近7天新增百分比
     */
//    @PreAuthorize("@ss.hasPermi('sale:getSevenDayNewEnquire')")
    @GetMapping("/getDauDetail")
    public AjaxResult getDauDetail(Map<String, Object> paramData) {
        Map<String, Object> result = dataEnquiriesServiceImpl.getDauDetail(paramData);
        return AjaxResult.success("success", result);
    }

    @GetMapping("/getTotalAIEngineCall")
    public AjaxResult getTotalAIEngineCall(Map<String, Object> paramData) {
        Map<String,Object> queryResult = dataListingsServiceImpl.getTotalAIEngineCall(paramData);
        Map<String, Object> result = new HashMap<>();
        result.put("aiEngineCall", queryResult.get("daily_count"));
        result.put("upOrDown", queryResult.get("ratio_percentage"));
        return AjaxResult.success("success", result);
    }

    @GetMapping("/getDataSourceStatus")
    public AjaxResult getDataSourceStatus(Map<String, Object> paramData) {
        Map<String, Object> result = new HashMap<>();
        Map<String,Object> queryResult = dataListingsServiceImpl.getDataSourceStatus(paramData);
        String successCount = Objects.isNull(queryResult.get("success_count")) ? "0" :queryResult.get("success_count").toString();
        String dataSourceStatus = successCount+ "/" +  queryResult.get("total_count");
        result.put("dataSourceStatus", dataSourceStatus);
        String growthRate = Objects.isNull(queryResult.get("growth_rate_percentage")) ? "0":queryResult.get("growth_rate_percentage").toString();
        if(Double.parseDouble(growthRate) < 0 ){
            growthRate = "0";
        }
        result.put("upOrDown",growthRate);
        return AjaxResult.success("success", result);
    }

    @GetMapping("/getDataProcessJob")
    public AjaxResult getDataProcessJob(Map<String, Object> paramData) {
        Map<String, Object> result = new HashMap<>();
        Map<String,Object> queryResult = dataListingsServiceImpl.getDataProcessJobDetail(paramData);
        result.put("allJobStatus", queryResult.get("overall_status"));
        result.put("upOrDown", queryResult.get("grouthSuccessRate"));
        return AjaxResult.success("success", result);
    }

    @GetMapping("/getUserActivityTrend")
    public AjaxResult getUserActivityTrend(Map<String, Object> paramData) {
        Map<String, Object> result = new HashMap<>();

        List<Map<String, Object>> queryResult = dataEnquiriesServiceImpl.getUserActivityTrend(paramData);
        queryResult.stream().forEach(map -> {
            result.put(map.get("login_date").toString(),map.get("dau"));
        });

        return AjaxResult.success("success", result);
    }

    @GetMapping("/getSystemLogDetail")
    public AjaxResult getSystemLogDetail(Map<String, Object> paramData) {
        SysOperLog operLog = new SysOperLog();
        List<SysOperLog> sysOperLogList = sysOperLogService.selectOperLogList(operLog).stream().filter(log -> StringUtils.isBlank(log.getErrorMsg())).limit(10).collect(Collectors.toList());
        List<SystemLogVo> orders = new ArrayList<>();
        sysOperLogList.forEach(log ->{
//            0=其它,1=后台用户,2=手机端用户
            orders.add(new SystemLogVo(log.getOperId().toString(), log.getOperName(), log.getOperIp(),
                    log.getOperTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate(),
                   operTypeName(log.getOperatorType().toString()) , SystemLogVo.OrderStatus.COMPLETED));
        });
        return AjaxResult.success("success", orders);
    }
    @GetMapping("/getSuburbDetail")
    public AjaxResult getSuburbDetail(Map<String, Object> paramData) {
        Map<String, Object> result = new HashMap<>();
        Map<String,List<SuburbDetailVo>> suburbMap = dataListingsServiceImpl.getSuburbDetail(paramData);
        return AjaxResult.success("success", suburbMap);

    }
    private String operTypeName(String operType){
        if("0".equals(operType)){
            return "other";
        }else if("1".equals(operType)){
            return "background user";
        }else if("2".equals(operType)){
            return "phone user";
        }else {
            return "none";
        }
    }
}
